package com.sfj.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.kaka.starter.mybatis.config.DataSetValueInterceptor;
import com.kaka.starter.mybatis.properties.MyBaitsProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.nologging.NoLoggingImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * @author kaka
 * @Date 2025/5/1
 */
@Configuration
@EnableConfigurationProperties({MyBaitsProperties.class})
public class MybatisPlugConfig implements ConfigurationCustomizer {

    private static final Logger logger = LoggerFactory.getLogger(MybatisPlugConfig.class);

    @Autowired
    private MyBaitsProperties myBaitsProperties;
    @Autowired
    private ConfigurableApplicationContext context;
    private static final String SPRING_PROFILES = "dev";


    @Bean
    @ConditionalOnProperty(name = "mybatis-plus.mapper-locations")
    public MybatisPlusInterceptor mybatisPlusInterceptor() throws Exception {

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        if (StringUtils.isNotEmpty(myBaitsProperties.getCreateUser())
                || StringUtils.isNotEmpty(myBaitsProperties.getCreateTime())) {
            interceptor.addInnerInterceptor(new DataSetValueInterceptor(myBaitsProperties));
        }
        //interceptor.addInnerInterceptor(new DataQueryByAuthInterceptor());
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.DM));

        logger.info("Mybatis plug Initializing Interceptor '{}'", interceptor.getInterceptors());
        return interceptor;
    }


    @Override
    public void customize(MybatisConfiguration configuration) {
        if (isDev()) {
            configuration.setLogImpl(NoLoggingImpl.class);
        } else {
            configuration.setLogImpl(Log4j2Impl.class);
        }
        logger.info("[CONFIG] Mybatis setLogImpl is {}", configuration.getLogImpl().getName());
    }


    private boolean isDev() {
        String[] profileStrs = context.getEnvironment().getActiveProfiles();
        final List<String> profileStrList = Arrays.asList(profileStrs);
        return profileStrList.contains(SPRING_PROFILES);
    }

}
